package com.cn.transfer.handle.impl.saleorder;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cn.transfer.common.constant.KeyConstant;
import com.cn.transfer.common.entity.DocumentApproval;
import com.cn.transfer.common.entity.VvSaSaleOrder;
import com.cn.transfer.common.entity.VvSaSaleOrderB;
import com.cn.transfer.common.http.ApiClient;
import com.cn.transfer.common.utils.ConnmeUtils;
import com.cn.transfer.common.vo.MessagePushVO;
import com.cn.transfer.common.vo.PurchaseOrderDetail;
import com.cn.transfer.handle.MessageStrategy;
import com.cn.transfer.mapper.VvSaSaleOrderBMapper;
import com.cn.transfer.mapper.VvSaSaleOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: 向伟典
 * @date: 2023/9/13 11:08
 * @Description: 当销售订单审核时
 */
@Slf4j
@Component
public class SaleOrderReviewImpl implements MessageStrategy {
    @Autowired
    private VvSaSaleOrderMapper vvSaSaleOrderMapper;

    @Autowired
    private VvSaSaleOrderBMapper vvSaSaleOrderBMapper;


    @Transactional
    @Override
    public void handle(MessagePushVO message) {
        DocumentApproval documentApproval = ConnmeUtils.mapToObject(message.getBizContent(), DocumentApproval.class);
        VvSaSaleOrder vvSaSaleOrder = vvSaSaleOrderMapper.byCodeSale(documentApproval.getVoucherCode());
        // 查询视图，这条数据是否存在
        int i1 = vvSaSaleOrderMapper.inquireIsExist(vvSaSaleOrder.getDocumentnumber());
        if (i1 == 0) {
            // 存入视图
            vvSaSaleOrderMapper.insertVVSaleOrder(vvSaSaleOrder);
            for (VvSaSaleOrderB vvSaSaleOrderB : vvSaSaleOrder.getVvsasaleorderblist()) {
                vvSaSaleOrderBMapper.insertSaleOrderDetail(vvSaSaleOrderB);
            }
        }
        Header[] originalHeaders = new Header[2];
        originalHeaders[0] = new BasicHeader("Authorization", "Bearer " + KeyConstant.JDY_KEY);
        originalHeaders[1] = new BasicHeader("Content-Type", "application/json;charset=utf-8");

        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "6500165a60a971000ab0ad28");
        parameter.put("entry_id", "65015e41ddd8340007a1698d");
        parameter.put("data", ConnmeUtils.convertEntityToMap(vvSaSaleOrder));
        String jsonSale = JSONUtil.toJsonStr(parameter);
        log.info("销售订单审核时发生的数据：==== " + jsonSale);
        JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/create", originalHeaders, jsonSale);
        log.info("销售订单审核时接收的数据：====" + jdySale);
    }

    @Override
    public String getMsgType() {
        return "SaleOrder_Audit";
    }
}
